import { defineStore } from "pinia";
import { 
  accountLoginRequest, 
  getUserInfoById, 
  getUserMenusByRoleId 
} from '@/service/login/login'
import type { IAccount } from '@/types'
import { localCache } from '@/utils/cache'
import router from '@/router/index'
import { LOGIN_TOKEN } from '@/global/constants'
import { mapMenusToRoutes } from '@/utils/map-menus'
import useMainStore from "../main/main";

interface ILoginState {
  token: string
  userInfo: any
  userMenus: any
}


const useLoginStore = defineStore('login', {
  //指定类型
  state: (): ILoginState => ({
    token: '',
    userInfo: {},
    userMenus: []
  }),
  actions: {
      async loginAccountAction(account: IAccount){
      
        const loginResult = await accountLoginRequest(account)
          const id = loginResult.data.id
          const token = loginResult.data.token
          this.token = token
          localCache.setCache(LOGIN_TOKEN, token)

          //获取登陆用户的详细信息
          const userInfoResult = await getUserInfoById(id)
          // console.log(userInfoResult)
          const userInfo = userInfoResult.data
          this.userInfo = userInfo
          localCache.setCache('userInfo', userInfo)
  
          //根据角色请求用户的权限(菜单)
          const getUserMenusResult = await getUserMenusByRoleId(this.userInfo.role.id)
          // console.log(getUserMenusResult)
          const userMenus = getUserMenusResult.data
          this.userMenus = userMenus
          localCache.setCache('userMenus', userMenus)
          
          //请求所有关于部门角色的数据 roles/departments
          const mainStore = useMainStore()
          mainStore.fetchEntireDataAction()


          //动态添加路由
          const routes = mapMenusToRoutes(userMenus)
          routes.forEach(route => router.addRoute('main', route))

          router.push('/main')   
      },
      /**
       * 刷新加载本地缓存
       */
      loadLocalCacheAction() {
        //1.用户进行刷新的时候默认加载数据  
        const token = localCache.getCache(LOGIN_TOKEN)
        const userInfo = localCache.getCache('userInfo')
        const userMenus = localCache.getCache('userMenus')
        if(token && userInfo && userMenus) {
          this.token = token
          this.userInfo = userInfo
          this.userMenus = userMenus
          
          //刷新的时候再请求所有关于部门角色的数据 roles/departments
          const mainStore = useMainStore()
          mainStore.fetchEntireDataAction()

          //动态添加路由
          const routes = mapMenusToRoutes(userMenus)
          routes.forEach(route => router.addRoute('main', route))
        }
      }
  }

})


export default useLoginStore